package com.example.usbcamera;

import android.content.Context;
import android.graphics.Bitmap;
import android.util.Base64;
import android.util.Log;
import android.widget.FrameLayout;
import androidx.annotation.NonNull;
import androidx.camera.core.*;
import androidx.camera.lifecycle.ProcessCameraProvider;
import androidx.camera.view.PreviewView;
import androidx.core.content.ContextCompat;
import androidx.lifecycle.LifecycleOwner;

import com.google.common.util.concurrent.ListenableFuture;

import java.io.ByteArrayOutputStream;
import java.util.concurrent.ExecutionException;

public class CameraXView extends FrameLayout {
    private PreviewView previewView;
    private ImageCapture imageCapture;

    public CameraXView(@NonNull Context context) {
        super(context);
        initCamera(context);
    }

    private void initCamera(Context context) {
        previewView = new PreviewView(context);
        this.addView(previewView, new LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT));

        final ListenableFuture<ProcessCameraProvider> cameraProviderFuture = ProcessCameraProvider.getInstance(context);

        cameraProviderFuture.addListener(() -> {
            try {
                ProcessCameraProvider cameraProvider = cameraProviderFuture.get();

                Preview preview = new Preview.Builder().build();
                imageCapture = new ImageCapture.Builder().build();

                CameraSelector cameraSelector = CameraSelector.DEFAULT_BACK_CAMERA;

                cameraProvider.unbindAll();

                preview.setSurfaceProvider(previewView.getSurfaceProvider());

                cameraProvider.bindToLifecycle(
                        (LifecycleOwner) context,
                        cameraSelector,
                        preview,
                        imageCapture
                );
            } catch (ExecutionException | InterruptedException e) {
                e.printStackTrace();
            }
        }, ContextCompat.getMainExecutor(context));
    }

    public void takePicture(OnPhotoTakenCallback callback) {
        if (imageCapture == null) return;

        imageCapture.takePicture(ContextCompat.getMainExecutor(getContext()),
                new ImageCapture.OnImageCapturedCallback() {
                    @Override
                    public void onCaptureSuccess(@NonNull ImageProxy image) {
                        Bitmap bitmap = toBitmap(image);
                        String base64 = bitmapToBase64(bitmap);
                        image.close();
                        callback.onTaken(base64);
                    }

                    @Override
                    public void onError(@NonNull ImageCaptureException exception) {
                        Log.e("CameraX", "Capture failed: " + exception.getMessage());
                        callback.onTaken(null);
                    }
                });
    }

    public interface OnPhotoTakenCallback {
        void onTaken(String base64);
    }

    private Bitmap toBitmap(ImageProxy image) {
        // 可以使用 YUV 转换库，也可以使用 Preview + Screenshot 实现
        return previewView.getBitmap(); // 简化方式，效果良好但可能低分辨率
    }

    private String bitmapToBase64(Bitmap bitmap) {
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        bitmap.compress(Bitmap.CompressFormat.JPEG, 90, baos);
        return Base64.encodeToString(baos.toByteArray(), Base64.NO_WRAP);
    }
}
